//
//  TranslationFilterView.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/3/13.
//  Copyright © 2025 考拉🐨. All rights reserved.
//

import UIKit
import Reusable
import SnapKit
import Localize_Swift

extension TranslationFilterView: NibLoadable {}

class TranslationFilterView: UIView {
    
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var backButton: UIButton!
    @IBOutlet weak var submitButton: UIButton!
    
    // 语言选择
    var requestLang: String = "" {
        didSet {
            if requestLang.isEmpty {
                return
            }
            if let uiModel = list.filter({ $0.id == 0 }).first {
                uiModel.list.forEach { model in
                    model.isSelected = false
                    if model.id == 0 && requestLang.contains("中") {
                        model.isSelected = true
                    }
                    if model.id == 1 && requestLang.contains("俄") {
                        model.isSelected = true
                    }
                }
            }
        }
    }
    // 地区选择
    var knowCityId: String = "" {
        didSet {
            if knowCityId.isEmpty {
                return
            }
            if let uiModel = list.filter({ $0.id == 1 }).first {
                let model = uiModel.list[0]
                model.id = knowCityId.sg.toInt
            }
        }
    }
    // 选择的地区名字
    var knowCityName: String = "" {
        didSet {
            if knowCityName.isEmpty {
                return
            }
            if let uiModel = list.filter({ $0.id == 1 }).first {
               let model = uiModel.list[0]
                model.name = knowCityName
            }
        }
    }
    
    // 专业选择
    var professionalIds: String = "" {
        didSet {
            if professionalIds.isEmpty {
                return
            }
            let ids = professionalIds.split(separator: ",") as! [String]
            if let uiModel = list.filter({ $0.id == 2 }).first {
                uiModel.list.forEach { model in
                    model.isSelected = false
                    if ids.contains(String(model.id)) {
                        model.isSelected = true
                    }
                }
            }
        }
    }
    // 价格选择
    var intentionScore: String = "" {
        didSet {
            if intentionScore.isEmpty {
                return
            }
            let scores = intentionScore.split(separator: ",") as! [String]
            if let uiModel = list.filter({ $0.id == 3 }).first {
                uiModel.list.forEach { model in
                    model.isSelected = false
                    if scores.contains(model.name) {
                        model.isSelected = true
                    }
                }
            }
        }
    }
    // 国籍 id
    var country: String = "" {
        didSet {
            if country.isEmpty {
                return
            }
            if let uiModel = list.filter({ $0.id == 1 }).first {
                let model = uiModel.list[0]
                model.id = country.sg.toInt
            }
        }
    }
    
    var cityList: [LoginCityModel] = []
    lazy var cityView: CountryPickerView = {
        CountryPickerView.loadFromNib()
    }()
    
    var didSelectedItemsBlock: (([TranslationFilterUIModel]) -> Void)?
    var list: [TranslationFilterUIModel] = [] {
        didSet {
            collectionView.reloadData()
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        list = TranslationFilterUIModel.dataSources()
        initUI()
        loadData()
        getSelectedCityList(isShow: false)
    }
    
    @IBAction func submitAction(_ sender: Any) {
        didSelectedItemsBlock?(list)
        isHidden = true
    }
    
    @IBAction func backAction(_ sender: Any) {
        isHidden = true
    }
}

private extension TranslationFilterView {
    func initUI() {
        addRoundedCorners(radius: 20)
        backButton.addRoundedCorners(radius: 4)
        submitButton.addRoundedCorners(radius: 20)
        submitButton.setTitle(LanguageManager.currentLanguageToText("确定", "Подтвердить"), for: .normal)
        
        cityView.didSelectedBlock = { [self] id, name in
            if let uiModel = list.filter({ $0.id == 1 }).first {
               let model = uiModel.list[0]
                model.id = id
                model.name = name
                collectionView.reloadData()
            }
            cityView.isHidden = true
        }
        cityView.closeBlock = {
            self.cityView.isHidden = true
        }
        addSubview(cityView)
        cityView.isHidden = true
        cityView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        let layout = UICollectionViewLeftAlignedLayout()
        collectionView.setCollectionViewLayout(layout, animated: true)
        collectionView.delegate = self
        collectionView.dataSource = self
        
        collectionView.backgroundColor = .white
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        collectionView.register(cellType: TranslationFilterItemCell.self)
        collectionView.register(cellType: TranslationFilterAreaItemCell.self)
        
        collectionView.register(supplementaryViewType: TranslationFilterReusableView.self, ofKind: UICollectionView.elementKindSectionHeader)
        collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "UICollectionReusableView")
        collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "UICollectionReusableView")
    }
    
    
    func getSelectedCityList(isShow: Bool) {
        
        let countryType = LanguageManager.isLanguageZH ? 0: 1
        
        let target = LoginAPI.cityList(country: countryType, pid: 0, isPort: true)
        YLRequest.request(target) { [self] result in
            switch result {
            case .success(let res):
                
                let dataArray = res.dataArray
                
                // 过滤掉请选择
                let list = JsonUtil.modelsFromArray(dataArray, LoginCityModel.self).filter({ $0.id != -2 })
                
                list.forEach { countryModel in
                    // 国家
                    countryModel.level = 0
                    countryModel.children.forEach { provinceModel in
                        // 省
                        provinceModel.pid = countryModel.id
                        provinceModel.level = 1
                        provinceModel.children.forEach { cityModel in
                            // 城市
                            cityModel.level = 2
                            cityModel.pid = provinceModel.id
                        }
                    }
                }
                cityList = list
                if isShow {
                    cityView.dataSources = cityList
                    cityView.isHidden = true
                }
                
            case .failure(let err):
                YLHUD.showHint(.error, err.errMsg)
            }
        }
    }
    
    
    func loadData() {
        let target = JavaAPI.getSelectStaffCondition
        YLRequest.request(target) { [self] result in
            switch result {
            case .success(let res):
                
                let dataDictionary = res.dataDictionary
                
                // 价格
                let codeTableList = JsonUtil.modelsFromArray(dataDictionary["codeTableList"] as! [Any], TranslationFilterModel.self)
                
                // 专业
                let priceScoreList = dataDictionary["priceScoreList"] as! [String]
                
                list.forEach { uiModel in
                    if uiModel.id == 3 {
                        // 价格选择
                        var arr: [TranslationFilterModel] = []
                        priceScoreList.forEach { price in
                            let model = TranslationFilterModel()
                            model.id = price.sg.toInt
                            model.name = price + "积分"
                            model.nameRu = price + "б."
                            arr.append(model)
                        }
                        uiModel.list = arr
                    }
                    
                    if uiModel.id == 2 {
                        // 专业方向
                        uiModel.list = codeTableList
                    }
                }
                collectionView.reloadData()
                
            case .failure(let err):
                YLHUD.showHint(.error, err.errMsg)
            }
        }
    }
}

extension TranslationFilterView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateLeftAlignedLayout {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        list.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let model = list[section]
        return model.list.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let uiModel = list[indexPath.section]
        if uiModel.id == 1 {
            let cell = collectionView.dequeueReusableCell(for: indexPath, cellType: TranslationFilterAreaItemCell.self)
            cell.model = uiModel.list[indexPath.row]
            cell.clearBlock = {
                if let uiModel = self.list.filter({ $0.id == 1 }).first {
                    let model = uiModel.list[0]
                    model.id = 0
                    model.name = "地区选择"
                    collectionView.reloadData()
                }
            }
            return cell
            
        }
        let cell = collectionView.dequeueReusableCell(for: indexPath, cellType: TranslationFilterItemCell.self)
        cell.model = uiModel.list[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let uiModel = list[indexPath.section]
        if uiModel.id == 1 {
            xLog("地区选择")
            if cityList.count == 0 {
                getSelectedCityList(isShow: true)
                return
            }
            
            cityView.dataSources = cityList
            cityView.isHidden = false
            return
        }
        let model = uiModel.list[indexPath.row]
        model.isSelected = !model.isSelected
        collectionView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let uiModel = list[indexPath.section]
        if uiModel.id == 1 {
            return CGSize(width: xScreenW - 32, height: 44 + 32)
        }
        let model = uiModel.list[indexPath.row]
        let name = LanguageManager.currentLanguageToText(model.name, model.nameRu)
        let width = name.sg.size(width: xScreenW, font: .systemFont(ofSize: 12)).width
        return CGSize(width: width + 24, height: 32)
    }
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        let model = list[section]
        if model.id == 1 {
            return .zero
        }
        return CGSize(width: xScreenW, height: 44)
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let reusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, for: indexPath, viewType: TranslationFilterReusableView.self)
            let model = list[indexPath.section]
            let title = LanguageManager.currentLanguageToText(model.title, model.titleRu)
            let subTitle = LanguageManager.currentLanguageToText(model.subTitle, model.subTitleRu)
            let text = NSMutableAttributedString(string: title + subTitle)
            text.color(UIColor(hex: "333333"))
            text.font(.systemFont(ofSize: 14, weight: .medium))
            
            if !subTitle.isEmpty {
                text.font(.systemFont(ofSize: 14, weight: .regular), range: text.string.inRange(of: subTitle).first!)
                text.color(UIColor(hex: "8C8C8C"), range: text.string.inRange(of: subTitle).first!)
            }
            reusableView.titleLabel.attributedText = text
            return reusableView
        }
        return collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "UICollectionReusableView", for: indexPath)
    }
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        .zero
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        10
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        10
    }
}


